﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace SocketSend
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            initSockte();
        }

        #region    Socket socketSend;
        Socket socketSend;
        #endregion

        public void initSockte()
        {
            #region Socket

            socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint point = new IPEndPoint(IPAddress.Parse(textBox1.Text.Trim()),
                Convert.ToInt32(textBox2.Text.Trim()));
            try
            {
                socketSend.Connect(point);    //连接服务器
                lblLog.Text = (string.Format("连接{0}服务器成功！", textBox1.Text.Trim()));

                Thread th = new Thread(Receive);      //创建TCP接收线程
                th.IsBackground = true;
                th.Start();
            }
            catch (Exception ee)
            {
                //  lblLog.Text = ee.ToString();
            }

            #endregion
        }


        #region Receive
        private void Receive()
        {

            while (true)
            {
                #region MyRegion

                try
                {
                    byte[] buffer = new byte[1024 * 1024 * 5];
                    int r = socketSend.Receive(buffer);
                    if (r == 0)
                    {
                        break;
                    }
                    string strMsg = Encoding.UTF8.GetString(buffer, 0, r);



                    this.Invoke(new EventHandler(delegate
                    {
                        lblLog.Text = "接收数据：" + strMsg;
                    }));

                }
                catch (Exception ex)
                {

                    this.Invoke(new EventHandler(delegate
                    {
                        lblLog.Text = "接收数据 Exception：" + ex.ToString();
                    }));

                }

                #endregion

                Thread.Sleep(100);
            }


        }


        #endregion

        private void button2_Click(object sender, EventArgs e)
        { 
            byte[] buffer = Encoding.UTF8.GetBytes(textBox3.Text);
            socketSend.Send(buffer);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(textBox4.Text);
            socketSend.Send(buffer);
        }
    }
}
